package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author : sunjun
 * @email : sunjun0207@163.com
 * @create 2019/11/15 17:56
 */
//后台管理-->用户认证和授权
@Component
public class SpringSecurityUserService implements UserDetailsService {
    //使用dubbo通过网络远程调用服务提供方
    //获取数据库中的用户信息
    @Reference
    private UserService userService;//注入userService去注册中心订阅服务

    /*
    后台管理-->根据用户名查询数据库获取用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.调用userService完成查询
        User user = userService.findByUsername(username);
        if(user == null){//执行查询的用户不存在
            return null;//将结果返回给框架
        }

        //定义一个list集合用来存储用户具有的角色和权限
        List<GrantedAuthority> list = new ArrayList<>();
        //2.动态为当前用户授予角色和授权
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {//遍历所有的角色
            //给每一个用户授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //取出角色具有的权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {//遍历所有的权限
                //给用户授权
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //创建一个授权用户并返回
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return securityUser;
    }
}
